package com.yoyo.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程相关工具类
 *
 * @author zyl
 * @Date 2021/6/27 -14:23
 */
@Slf4j
public class Threads {


    /**
     * 停止线程池
     * 先使用shutdown 停止接受新任务并尝试完成自己已经存在的的任务
     * 如果超时 则调用shutdownNow 取消在workQueue中Pending的任务 并终端所有阻塞函数
     * 如果有超时则乔治退出
     * 另外在shutdown时线程本身被调用中中断做了处理
     *
     * @param executor
     */
    public static void shutdownAndAwaitTermination(ScheduledExecutorService executor) {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(120, TimeUnit.SECONDS)) {
                    executor.shutdown();
                    if (!executor.awaitTermination(120, TimeUnit.SECONDS)) {
                        log.info("pool did not terminate ");
                    }
                }
            } catch (InterruptedException e) {
                executor.shutdown();
                Thread.currentThread().interrupt();
            }
        }
    }
    /**
     * 打印线程异常信息
     */
    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>)
        {
            try
            {
                Future<?> future = (Future<?>) r;
                if (future.isDone())
                {
                    future.get();
                }
            }
            catch (CancellationException ce)
            {
                t = ce;
            }
            catch (ExecutionException ee)
            {
                t = ee.getCause();
            }
            catch (InterruptedException ie)
            {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null)
        {
            log.error(t.getMessage(), t);
        }
    }
}
